import { defineMock } from "./base";
import type { MockRequest } from "vite-plugin-mock-dev-server";

const DPHLPDOC_URL = "settings/current-protection/dphlpdoc/";

// 定义设置项类型
interface SettingItem {
  id: string;
  type: string;
  paramWriteAccess: boolean;
  options: string[];
  createTime: string;
  updateTime: string;
  ParameterName: string;
  "IED Value": string | number;
  unit: string | null;
  min: number | null;
  max: number | null;
  step: number;
  group: number;
}

const types = ["Numerical", "SingleChoice", "String"];

function generateSettingItem(id: number, type: string): SettingItem {
  const item: SettingItem = {
    id: id.toString(),
    type,
    paramWriteAccess: true,
    options: [],
    createTime: "2025-05-28 12:00:00",
    updateTime: "2025-05-28 12:00:00",
    ParameterName: "",
    "IED Value": "",
    unit: null,
    min: null,
    max: null,
    step: 0,
    group: 0,
  };
  if (type === "Numerical") {
    item.ParameterName = "# Operate delay time";
    item["IED Value"] = 0.04;
    item.unit = "s";
    item.min = 0.04;
    item.max = 200.0;
    item.step = 0.01;
    item.type = "number";
    item.group = 1;
  } else if (type === "SingleChoice") {
    item.ParameterName = "# Type of reset curve";
    item["IED Value"] = "Immediate";
    item.unit = null;
    item.min = null;
    item.max = null;
    item.step = 0;
    item.type = "enum";
    item.options = ["Immediate", "Def time reset", "Inverse reset"];
    item.group = 2;
  } else if (type === "String") {
    item.ParameterName = "# Type of reset curve";
    item["IED Value"] = "Immediate";
    item.unit = null;
    item.min = null;
    item.max = null;
    item.step = 0;
    item.type = "string";
    item.group = 3;
  }
  return item;
}

// 内部数据源
let settingList: SettingItem[] = Array.from({ length: 100 }).map((_, id) =>
  generateSettingItem(id, types[id % 3])
);

export default defineMock([
  // 列表查询
  {
    url: `${DPHLPDOC_URL}list`,
    method: ["GET"],
    body: (req: MockRequest) => {
      const { page = 1, pageSize = 20 } = req.query || {};
      const start = (Number(page) - 1) * Number(pageSize);
      const end = start + Number(pageSize);
      const data = settingList.slice(start, end);
      return {
        code: "00000",
        data: {
          list: data,
          total: settingList.length,
        },
        msg: "ok",
      };
    },
  },
  // offset 分页查询
  {
    url: `${DPHLPDOC_URL}offset-list`,
    method: ["GET"],
    body: (req: MockRequest) => {
      const { offset = 0, limit = 20, keywords = "", fixedValueArea = 0 } = req.query || {};
      // 改正下面的代码
      console.log(
        "fixedValueArea参数值和类型分别为：",
        fixedValueArea,
        "type:",
        typeof fixedValueArea
      );
      const start = offset;
      const end = start + limit;
      let data: SettingItem[] = [];
      let total = 0;
      if (+fixedValueArea === 0) {
        data = settingList.slice(start, end);
        total = settingList.length;
      } else {
        const filteredData = settingList.filter((item) => item.group === +fixedValueArea);
        data = filteredData.slice(start, end);
        total = filteredData.length;
      }
      return {
        code: "00000",
        data: {
          list: data,
          total: total,
        },
        msg: "ok",
      };
    },
  },
  // 批量删除
  {
    url: `${DPHLPDOC_URL}batch-delete`,
    method: ["POST"],
    body: (req: MockRequest) => {
      const { ids } = req.body || {};
      if (!Array.isArray(ids)) {
        return { code: "10001", msg: "参数错误，缺少ids数组" };
      }
      settingList = settingList.filter((item) => !ids.includes("" + item.id));
      return { code: "00000", data: null, msg: `已删除${ids.length}项` };
    },
  },
  // 批量更新
  {
    url: `${DPHLPDOC_URL}batch-update`,
    method: ["POST"],
    body: (req: MockRequest) => {
      const updates = req.body || [];
      if (!Array.isArray(updates)) {
        return { code: "10001", msg: "参数错误，缺少updates数组" };
      }
      let updateCount = 0;
      updates.forEach((update: Partial<SettingItem> & { id: string }) => {
        const idx = settingList.findIndex((item) => item.id === update.id);
        if (idx !== -1) {
          settingList[idx] = {
            ...settingList[idx],
            ...update,
            updateTime: new Date().toISOString(),
          };
          updateCount++;
        }
      });
      return { code: "00000", data: null, msg: `已更新${updateCount}项` };
    },
  },
  // hmi/setting-area 查询定值区列表
  {
    url: "hmi/setting-area/list",
    method: ["GET"],
    body: () => {
      return {
        code: "00000",
        data: [1, 2, 3],
        msg: "一切ok",
      };
    },
  },
  // /device/settings/current-protection/dphlpdoc
  {
    url: `device/settings/current-protection/dphlpdoc/offset-list`,
    method: ["GET"],
    body: (req: MockRequest) => {
      const { offset = 0, limit = 20, keywords = "", fixedValueArea = 0 } = req.query || {};
      // 改正下面的代码
      console.log(
        "fixedValueArea参数值和类型分别为：",
        fixedValueArea,
        "type:",
        typeof fixedValueArea
      );
      const start = offset;
      const end = start + limit;
      let data: SettingItem[] = [];
      let total = 0;
      if (+fixedValueArea === 0) {
        data = settingList.slice(start, end);
        total = settingList.length;
      } else {
        const filteredData = settingList.filter((item) => item.group === +fixedValueArea);
        data = filteredData.slice(start, end);
        total = filteredData.length;
      }
      return {
        code: "00000",
        data: {
          list: data,
          total: total,
        },
        msg: "ok",
      };
    },
  },
  {
    url: `device/settings/current-protection/dphlpdoc/batch-update`,
    method: ["POST"],
    body: (req: MockRequest) => {
      const updates = req.body || [];
      if (!Array.isArray(updates)) {
        return { code: "10001", msg: "参数错误，缺少updates数组" };
      }
      let updateCount = 0;
      updates.forEach((update: Partial<SettingItem> & { id: string }) => {
        const idx = settingList.findIndex((item) => item.id === update.id);
        if (idx !== -1) {
          settingList[idx] = {
            ...settingList[idx],
            ...update,
            updateTime: new Date().toISOString(),
          };
          updateCount++;
        }
      });
      return { code: "00000", data: null, msg: `已更新${updateCount}项` };
    },
  },
]);
